using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;

namespace Dazzle
{
    /// <summary>
    /// The object created by CreateDataAdviseHolder is not threadsafe!
    /// Implementing DAdvise and friends is very complicated so we just do it
    /// all in a thread.  We cannot use the main thread because it may already 
    /// be calling the client site, which is in turn calling (e.g.) DUnadvise.
    /// </summary>
    class DataAdviseThread
    {
        Thread thrd;
        IDataAdviseHolder dataAdviseHolder;
        HiddenForm hiddenForm;
        EventWaitHandle initialised = new EventWaitHandle(false, EventResetMode.ManualReset);
        ILog logger = LogManager.GetLogger(typeof(DataAdviseThread));

        public DataAdviseThread()
        {
            thrd = new Thread(Run);
            thrd.Name = "DataAdvise";
            thrd.Start();
        }

        public IDataAdviseHolder Holder { get { return dataAdviseHolder; } }

        void Run()
        {
            int res = Win32.CreateDataAdviseHolder(out dataAdviseHolder);
            Debug.Assert(res == Win32.S_OK);
            hiddenForm = new HiddenForm();
            Debug.Assert(hiddenForm != null);
            initialised.Set();
            Application.Run();
        }

        /// <summary>Makes invocation of Invoke more concise with parameter-
        /// less methods.</summary>
        public void Invoke(string action, MethodInvoker invoker)
        {
            initialised.WaitOne();
            logger.Debug("DataAdviseThread " + action);
            //using (new IndentLog("DataAdviseThread "+action)) {
                hiddenForm.Invoke((Delegate)invoker);
           // }
        }

        public void Stop()
        {
            thrd.Abort();
        }
    }
}
